﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Buca.Application.aBigTime.WindowsForm.FormBase.PropertyGrid;
using Buca.Application.aBigTime.WindowsForm.Resources;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;

namespace Buca.Application.aBigTime.WindowsForm.FormBase
{
    public partial class FrmBaseVoucherList : Form
    {
        #region Variables

        /// <summary>
        /// 
        /// </summary>
        public enum ActionMode
        {
            AddNew = 0,
            Edit = 1,
            Delete = 2,
            None = 3
        }
        /// <summary>
        /// The e action mode
        /// </summary>
        public ActionMode eActionMode;
        /// <summary>
        /// The columns collection
        /// </summary>
        public List<XtraColumn> ColumnsCollection = new List<XtraColumn>();
        /// <summary>
        /// The primary key value
        /// </summary>
        public string PrimaryKeyValue;

        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the form detail.
        /// </summary>
        /// <value>
        /// The form detail.
        /// </value>
        [Category("BaseProperty")]
        public string FormDetail { get; set; }
        /// <summary>
        /// Gets or sets the namespace form.
        /// </summary>
        /// <value>
        /// The namespace form.
        /// </value>
        [Category("BaseProperty")]
        public string NamespaceForm { get; set; }
        /// <summary>
        /// Gets or sets the table primary key.
        /// </summary>
        /// <value>
        /// The table primary key.
        /// </value>
        [Category("BaseProperty")]
        public string TablePrimaryKey { get; set; }
        /// <summary>
        /// Gets or sets the form caption.
        /// </summary>
        /// <value>
        /// The form caption.
        /// </value>
        [Category("BaseProperty")]
        public string FormCaption { get; set; }
        /// <summary>
        /// Gets or sets the row selected.
        /// </summary>
        /// <value>
        /// The row selected.
        /// </value>
        [Category("BaseProperty")]
        public int RowSelected { get; set; }

        #endregion

        #region Functions

        /// <summary>
        /// Initializes the layout.
        /// </summary>
        private void InitializeLayout()
        {
            Text = FormCaption;
        }
        /// <summary>
        /// Loads the data.
        /// </summary>
        private void LoadData()
        {
            try
            {
                grdMain.BeginUpdate();
                LoadDataIntoGrid();
                LoadGridLayout();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, ResourceHelper.GetResourceValueByName("ResExceptionCaption"));
                grdMain.EndUpdate();
            }
            finally { grdMain.EndUpdate(); }
        }
        /// <summary>
        /// Loads the grid layout.
        /// </summary>
        private void LoadGridLayout()
        {
            if (ColumnsCollection != null)
            {
                foreach (var column in ColumnsCollection)
                {
                    if (column.ColumnVisible == true)
                    {
                        grdView.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        grdView.Columns[column.ColumnName].VisibleIndex = column.ColumnPosition;
                        grdView.Columns[column.ColumnName].Width = column.ColumnWith;
                    }
                    else grdView.Columns[column.ColumnName].Visible = false;
                }
            }
        }
        /// <summary>
        /// Sets the row selected.
        /// </summary>
        private void SetRowSelected(int rowHandler = 0)
        {
            grdView.OptionsSelection.EnableAppearanceFocusedRow = true;
            grdView.OptionsSelection.EnableAppearanceFocusedCell = false;
            if (grdView.RowCount > 0) grdView.FocusedRowHandle = rowHandler;
        }
        /// <summary>
        /// Gets the row value selected.
        /// </summary>
        /// <returns></returns>
        public void GetRowValueSelected()
        {
            try
            {
                if (grdMain.DataSource != null)
                {
                    var rowHandle = grdView.FocusedRowHandle;
                    PrimaryKeyValue = grdView.GetRowCellValue(rowHandle, TablePrimaryKey) != null ? grdView.GetRowCellValue(rowHandle, TablePrimaryKey).ToString() : null;
                }
            }
            catch (Exception ex) { XtraMessageBox.Show(ex.Message, ResourceHelper.GetResourceValueByName("ResExceptionCaption")); }
        }
        /// <summary>
        /// Shows the form detail.
        /// </summary>
        private void ShowFormDetail()
        {
            using (frmBaseVoucherDetail frmDetail = GetFormDetail())
            {
                frmDetail.eActionMode = (frmBaseVoucherDetail.ActionMode)eActionMode;
                frmDetail.KeyValue = frmDetail.eActionMode == frmBaseVoucherDetail.ActionMode.AddNew ? null : PrimaryKeyValue;
                frmDetail.PostKeyValue += FrmDetail_PostKey;
                if (frmDetail.ShowDialog() == DialogResult.OK) { }
            }
        }
        /// <summary>
        /// The FRM base category detail
        /// </summary>
        private frmBaseVoucherDetail GetFormDetail()
        {
            try
            {
                frmBaseVoucherDetail frmDetail = new frmBaseVoucherDetail();
                Type typeOfForm = Assembly.GetExecutingAssembly().GetType(NamespaceForm + "." + FormDetail);
                return typeOfForm != null ? frmDetail = (frmBaseVoucherDetail)Activator.CreateInstance(typeOfForm) : null;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, ResourceHelper.GetResourceValueByName("ResExceptionCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
        /// <summary>
        /// Sets the row after update.
        /// </summary>
        private void SetRowAfterUpdate()
        {
            if (grdView.RowCount > 0)
            {
                GridColumn xtraColumn = grdView.Columns[TablePrimaryKey];
                for (int i = 0; i < grdView.RowCount; i++)
                {
                    var currentValue = grdView.GetRowCellValue(i, xtraColumn).ToString();
                    if (PrimaryKeyValue == currentValue) { RowSelected = i; break; }
                }
                SetRowSelected(RowSelected);
            }
        }
        /// <summary>
        /// FRMs the detail_ post key.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="data">The data.</param>
        public void FrmDetail_PostKey(object sender, string data)
        {
            PrimaryKeyValue = data;
        }

        #endregion

        #region Functions overrides

        /// <summary>
        /// Loads the data into grid.
        /// </summary>
        protected virtual void LoadDataIntoGrid()
        {
        }
        /// <summary>
        /// Deletes the grid.
        /// </summary>
        protected virtual void DeleteGrid()
        {
        }
        /// <summary>
        /// Adds the data.
        /// </summary>
        protected virtual void AddData()
        {
            eActionMode = ActionMode.AddNew;
            ShowFormDetail();
            LoadData();
        }
        /// <summary>
        /// Adds the data.
        /// </summary>
        protected virtual void EditData()
        {
            eActionMode = ActionMode.Edit;
            ShowFormDetail();
            LoadData();
        }

        #endregion

        #region Events

        /// <summary>
        /// Initializes a new instance of the <see cref="FrmBaseVoucherList"/> class.
        /// </summary>
        public FrmBaseVoucherList()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Handles the Load event of the FrmBaseVoucherList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void FrmBaseVoucherList_Load(object sender, EventArgs e)
        {
            InitializeLayout();
            LoadData();
            SetRowSelected(RowSelected);
            GetRowValueSelected();
        }
        /// <summary>
        /// Handles the RowClick event of the grdView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DevExpress.XtraGrid.Views.Grid.RowClickEventArgs"/> instance containing the event data.</param>
        private void grdView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            GetRowValueSelected();
        }
        /// <summary>
        /// Handles the ItemClick event of the mnuAddNew control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DevExpress.XtraBars.ItemClickEventArgs"/> instance containing the event data.</param>
        private void mnuAddNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AddData();
            SetRowAfterUpdate();
            GetRowValueSelected();
        }
        /// <summary>
        /// Handles the ItemClick event of the mnuEdit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DevExpress.XtraBars.ItemClickEventArgs" /> instance containing the event data.</param>
        private void mnuEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            EditData();
            SetRowAfterUpdate();
            GetRowValueSelected();
        }
        /// <summary>
        /// Handles the ItemClick event of the mnuDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DevExpress.XtraBars.ItemClickEventArgs"/> instance containing the event data.</param>
        private void mnuDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                var result = XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResDeleteContent"), ResourceHelper.GetResourceValueByName("ResDeleteCaption"),
                                                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (result == DialogResult.OK)
                {
                    DeleteGrid();
                    XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResDeleteResult"), ResourceHelper.GetResourceValueByName("ResDeleteCaption"));
                }
            }
            catch (Exception ex) { XtraMessageBox.Show(ex.Message, ResourceHelper.GetResourceValueByName("ResExceptionCaption")); }
            finally
            {
                LoadData();
                SetRowSelected();
                GetRowValueSelected();
            }
        }
        /// <summary>
        /// Handles the ItemClick event of the mnuRefresh control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DevExpress.XtraBars.ItemClickEventArgs"/> instance containing the event data.</param>
        private void mnuRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LoadData();
            SetRowSelected();
            GetRowValueSelected();
        }
        /// <summary>
        /// Handles the ItemClick event of the mnuExit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DevExpress.XtraBars.ItemClickEventArgs"/> instance containing the event data.</param>
        private void mnuExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Close();
        }
        /// <summary>
        /// Handles the DoubleClick event of the grdMain control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void grdMain_DoubleClick(object sender, EventArgs e)
        {
            EditData();
            SetRowAfterUpdate();
            GetRowValueSelected();
        }

        #endregion
    }
}